package com.wzt.lianfirecontrol.fragment.xiaokongshi;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.activity.ShowFragActivity;
import com.wzt.lianfirecontrol.adapter.BaseRecyclerAdapter;
import com.wzt.lianfirecontrol.adapter.xiaokongshi.RecordItemAdapter;
import com.wzt.lianfirecontrol.adapter.xiaokongshi.XksPersonAdapter;
import com.wzt.lianfirecontrol.adapter.xiaokongshi.XksProblemAdapter;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.function.xiaokongshi.XksRecordModel;
import com.wzt.lianfirecontrol.bean.recode.function.xiaokongshi.XksRecordProblemModel;
import com.wzt.lianfirecontrol.bean.recode.function.xiaokongshi.XksRecordUserModel;
import com.wzt.lianfirecontrol.bean.recode.user.RoleConstant;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.GildeUtils;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.PreferencesUtils;
import com.wzt.lianfirecontrol.utils.ScreenUtils;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DutyDetailFragment extends BaseFragment {

    private BaseActivity activity;
    private Bundle bundle;
    private View itemContentView;

    /**
     * 值班时间
     */
    private LinearLayout ll_zhiban_time;
    private TextView tv_zhiban_time;
    private TextView tv_one_more_day;
    private View v_time_line;
    /**
     * 值班人员
     */
    private LinearLayout ll_person_name;
    private RecyclerView rlv_person_list;
    private XksPersonAdapter xksPersonAdapter;

    /**
     * 值班人员签字
     */
    private LinearLayout ll_user_sign;
    private RelativeLayout rl_up_sign;
    private ImageView iv_up_sign;
    /**
     * 上传或者显示图片
     */
    private View include_play_photo_three;
    private RelativeLayout rl_device_photo_1;
    private ImageView iv_device_photo_1;
    private RelativeLayout rl_device_photo_2;
    private ImageView iv_device_photo_2;
    private RelativeLayout rl_device_photo_3;
    private ImageView iv_device_photo_3;
    /**
     * 值班事项
     */
    private RecyclerView rlv_item_list;
    private RecordItemAdapter recordItemAdapter;

    /**
     * 异常记录
     */
    private LinearLayout ll_yichang;
    private RecyclerView rlv_yichang_list;
    private LinearLayoutManager linearLayoutManager;
    private XksProblemAdapter xksProblemAdapter;

    private View include_no_data;
    private View include_no_net;
    private View include_progress_bar;

    private static final int UPDATE_REQUEST_WHAT = 2;

    private XksRecordModel xksRecordModel;// 1查看 2交接
    private boolean isChaKan = false;

    private LinearLayout ll_bottom_btn;
    private Button bt_yichang;
    private Button bt_zhengchang;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            bundle = getArguments();
            if (null != bundle){
                xksRecordModel = (XksRecordModel) bundle.getSerializable("XksRecordModel");
            }
            if (null == xksRecordModel){
                ToastUtils.showToast(activity, "数据错误");
                activity.finish();
            }
            activity = getMyActivity();
            itemContentView = inflater.inflate(R.layout.f_duty_detail, container, false);
            initView();
            setDetailData(xksRecordModel);
            if (isChaKan) {
                setListData(xksRecordModel.getRecordProblems());
            }
            PreferencesUtils.putString(activity, ConstData.YICHANGREFRESH, "1");
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {

        initYiChangList();

        initHeadView();

        initBottomView();

        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        include_progress_bar.setVisibility(View.GONE);
        InitView.instance().initProgressBar(activity, include_progress_bar);

        include_no_data = itemContentView.findViewById(R.id.include_no_data);
        include_no_data.setVisibility(View.GONE);

        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setVisibility(View.GONE);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData();
            }
        });
    }

    private void initHeadView() {

        View headView = LayoutInflater.from(activity).inflate(R.layout.head_duty_list, rlv_yichang_list, false);
        xksProblemAdapter.setHeaderView(headView);
        initZhiBanPerson(headView);

        initDeviceStatusPhoto(headView);

        rlv_item_list = headView.findViewById(R.id.rlv_item_list);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity);
        rlv_item_list.setLayoutManager(linearLayoutManager);
        recordItemAdapter = new RecordItemAdapter(activity);
        recordItemAdapter.setDetail(true);
        rlv_item_list.setAdapter(recordItemAdapter);

        ll_yichang = headView.findViewById(R.id.ll_yichang);
    }

    private void initZhiBanPerson(View headView) {
        ll_zhiban_time = headView.findViewById(R.id.ll_zhiban_time);
        tv_zhiban_time = headView.findViewById(R.id.tv_zhiban_time);
        tv_one_more_day = headView.findViewById(R.id.tv_one_more_day);
        v_time_line = headView.findViewById(R.id.v_time_line);
        rlv_person_list = headView.findViewById(R.id.rlv_person_list);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        rlv_person_list.setLayoutManager(linearLayoutManager);
        xksPersonAdapter = new XksPersonAdapter(activity);
        xksPersonAdapter.setDetail(true);
        rlv_person_list.setAdapter(xksPersonAdapter);

        ll_user_sign = headView.findViewById(R.id.ll_user_sign);
        rl_up_sign = headView.findViewById(R.id.rl_up_sign);
        iv_up_sign = headView.findViewById(R.id.iv_up_sign);
        int width = (ScreenUtils.getScreenWidth(activity) - Utils.dip2px(activity, 90)) / 3;
        rl_up_sign.getLayoutParams().width = width;
        rl_up_sign.getLayoutParams().height = width;
    }

    private void initYiChangList() {
        rlv_yichang_list = itemContentView.findViewById(R.id.rlv_yichang_list);
        linearLayoutManager = new LinearLayoutManager(activity);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        rlv_yichang_list.setLayoutManager(linearLayoutManager);
        xksProblemAdapter = new XksProblemAdapter(activity);
        xksProblemAdapter.setDetail(true);
        rlv_yichang_list.setAdapter(xksProblemAdapter);
        xksProblemAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<XksRecordProblemModel>() {
            @Override
            public void onItemClick(View v, int position, XksRecordProblemModel data) {
                if (!UserInfoModel.isSelfCompany(activity)){
                   // ToastUtils.showToast(activity, ConstData.ERROR_COMPANY_MSG);
                    return;
                }
                Bundle skipToBundle = new Bundle();
                skipToBundle.putSerializable("data", data);
                BannerModel bannerModel = new BannerModel();
                bannerModel.setActionType(ConstData.SHOWFRAG);
                bannerModel.setActionValue(ConstData.UNUSUALDETAIL);
                bannerModel.setActionTitle( "问题详情");
                activity.setClickAction(bannerModel, skipToBundle);
            }
        });

    }

    private void initDeviceStatusPhoto(View headView) {
        include_play_photo_three = headView.findViewById(R.id.include_play_photo_three);
        include_play_photo_three.setVisibility(View.VISIBLE);
        rl_device_photo_1 = include_play_photo_three.findViewById(R.id.rl_device_photo_1);
        iv_device_photo_1 = include_play_photo_three.findViewById(R.id.iv_device_photo_1);
        rl_device_photo_2 = include_play_photo_three.findViewById(R.id.rl_device_photo_2);
        iv_device_photo_2 = include_play_photo_three.findViewById(R.id.iv_device_photo_2);
        rl_device_photo_3 = include_play_photo_three.findViewById(R.id.rl_device_photo_3);
        iv_device_photo_3 = include_play_photo_three.findViewById(R.id.iv_device_photo_3);

        int width = (ScreenUtils.getScreenWidth(activity) - Utils.dip2px(activity, 90)) / 3;
        rl_device_photo_1.getLayoutParams().width = width;
        rl_device_photo_1.getLayoutParams().height = width;
        rl_device_photo_2.getLayoutParams().width = width;
        rl_device_photo_2.getLayoutParams().height = width;
        rl_device_photo_3.getLayoutParams().width = width;
        rl_device_photo_3.getLayoutParams().height = width;
    }

    private void initBottomView() {
        ll_bottom_btn = itemContentView.findViewById(R.id.ll_bottom_btn);
        bt_yichang = itemContentView.findViewById(R.id.bt_yichang);
        bt_zhengchang = itemContentView.findViewById(R.id.bt_zhengchang);
    }

    /**
     * 获取列表
     */
    private void initZhengChangHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", xksRecordModel.getId());
        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new InfoListListHttpHelper(activity, Url.XKS_DETAIL_UPDATE_URL, UPDATE_REQUEST_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new InfoListParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }

    private class InfoListListHttpHelper extends HttpHelper{

        public InfoListListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class InfoListParseJsonData extends ParseJsonData {

        public InfoListParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            if (msg.what == UPDATE_REQUEST_WHAT && ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
                PreferencesUtils.putString(activity, ConstData.NEEDREFRESH, "0");
                activity.finish();
            }
            return;
        }
    }

    private void setDetailData(final XksRecordModel detailModel) {
        if (null != detailModel && !StringUtils.isEmpty(detailModel.getStatus())){
            if ("4".equals(detailModel.getStatus()) || "5".equals(detailModel.getStatus())){
                isChaKan = true;
            }
            include_no_data.setVisibility(View.GONE);
            setZhiBanPersonData(detailModel);
            setDeviceStatusPhoto(detailModel);

            if (null != detailModel.getRecordItems() && detailModel.getRecordItems().size() > 0){
                recordItemAdapter.clear();
                recordItemAdapter.addDatas(detailModel.getRecordItems());
                rlv_item_list.setVisibility(View.VISIBLE);
            }else {
                rlv_item_list.setVisibility(View.GONE);
            }

            switch (detailModel.getStatus()){//1：待值班；2：值班中；3：未值班；4：待交接；5：已完成
                case "1":
                case "3":
                    ToastUtils.showToast(activity, "任务未开始或已结束");
                   activity.finish();
                    break;
                case "2":
                case "5":
                    ll_bottom_btn.setVisibility(View.GONE);
                    break;
                case "4":
                    ll_bottom_btn.setVisibility(View.VISIBLE);
                    bt_yichang.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!UserInfoModel.isSelfCompany(activity)){
                               // ToastUtils.showToast(activity, ConstData.ERROR_COMPANY_MSG);
                                return;
                            }
                            UserInfoModel userInfoModel = UserInfoModel.getUserInfo(activity);
                            if (userInfoModel.getRoleAlias().contains(RoleConstant.ROLE_DUTY)) {
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("data", xksRecordModel);
                                activity.setClickAction(ConstData.SHOWFRAG, ConstData.ADDUNUSUAL,
                                        "添加问题", null,  bundle);
                            }else {
                                ToastUtils.showToast(activity, "非值班员用户");
                            }
                        }
                    });
                    bt_zhengchang.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!UserInfoModel.isSelfCompany(activity)){
                               // ToastUtils.showToast(activity, ConstData.ERROR_COMPANY_MSG);
                                return;
                            }
                            UserInfoModel userInfoModel = UserInfoModel.getUserInfo(activity);
                            if (userInfoModel.getRoleAlias().contains(RoleConstant.ROLE_DUTY)) {
                                initZhengChangHttpHelper();
                            }else {
                                ToastUtils.showToast(activity, "非值班员用户");
                            }
                        }
                    });
                    break;
            }

        }else {
            include_no_data.setVisibility(View.VISIBLE);
        }
    }

    private void setZhiBanPersonData(XksRecordModel detailModel) {
        String startTime = detailModel.getClassStartTimeStr();
        String endTime = detailModel.getClassEndTimeStr();
        if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
            // 2020-06-14 06:00:00
            ll_zhiban_time.setVisibility(View.VISIBLE);
            v_time_line.setVisibility(View.VISIBLE);
            tv_zhiban_time.setText(startTime + "-" + endTime);
            tv_zhiban_time.setText(startTime + "-" + endTime.split(" ")[1]);
            if (startTime.startsWith(endTime.split(" ")[0])){
                tv_one_more_day.setText("");
                tv_one_more_day.setVisibility(View.GONE);
            }else {
                tv_one_more_day.setText("+1天");
                tv_one_more_day.setVisibility(View.VISIBLE);
            }
        }else {
            tv_zhiban_time.setText("");
            ll_zhiban_time.setVisibility(View.GONE);
            v_time_line.setVisibility(View.GONE);
            tv_one_more_day.setVisibility(View.GONE);
        }

        if (null != detailModel.getRecordUsers() && detailModel.getRecordUsers().size() > 0){
            List<UserInfoModel> userInfoModels = new ArrayList<>();
            for (XksRecordUserModel model:detailModel.getRecordUsers()) {
                UserInfoModel userInfoModel = new UserInfoModel();
                userInfoModel.setRealName(model.getRealName());
                userInfoModel.setPhone(model.getPhone());
                userInfoModel.setId(model.getUserId());
                userInfoModels.add(userInfoModel);
            }
            xksPersonAdapter.clear();
            xksPersonAdapter.addDatas(userInfoModels);
            rlv_person_list.setVisibility(View.VISIBLE);
        }else {
            rlv_person_list.setVisibility(View.GONE);
        }


        if (!StringUtils.isEmpty(detailModel.getSignImg()) && detailModel.getSignImg().startsWith("http")){
            ll_user_sign.setVisibility(View.VISIBLE);
            GildeUtils.loadImageCorner(activity, iv_up_sign, detailModel.getSignImg());
            iv_up_sign.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((ShowFragActivity)activity).setShowImg(detailModel.getSignImg());
                }
            });
        }else {
            ll_user_sign.setVisibility(View.GONE);
        }
    }

    private void setDeviceStatusPhoto(XksRecordModel detailModel) {
        String[] equImgs = detailModel.getEquImgs().split(",");
        if (equImgs.length > 0 && equImgs[0].startsWith("http")){
            rl_device_photo_1.setVisibility(View.VISIBLE);
            GildeUtils.loadImageCorner(activity, iv_device_photo_1, equImgs[0]);
            rl_device_photo_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((ShowFragActivity)activity).setShowImg(equImgs[0]);
                }
            });
        }else {
            rl_device_photo_1.setVisibility(View.INVISIBLE);
        }
        if (equImgs.length > 1){
            rl_device_photo_2.setVisibility(View.VISIBLE);
            GildeUtils.loadImageCorner(activity, iv_device_photo_2, equImgs[1]);
            iv_device_photo_2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((ShowFragActivity)activity).setShowImg(equImgs[1]);
                }
            });
        }else {
            rl_device_photo_2.setVisibility(View.INVISIBLE);
        }
        if (equImgs.length > 2){
            rl_device_photo_3.setVisibility(View.VISIBLE);
            GildeUtils.loadImageCorner(activity, iv_device_photo_3, equImgs[2]);
            rl_device_photo_3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((ShowFragActivity)activity).setShowImg(equImgs[2]);
                }
            });
        }else {
            rl_device_photo_3.setVisibility(View.INVISIBLE);
        }
    }

    private void setListData(List<XksRecordProblemModel> list) {
        xksProblemAdapter.clear();
        if (null == list || list.size() == 0){
            ll_yichang.setVisibility(View.GONE);
            return;
        }
        ll_yichang.setVisibility(View.VISIBLE);
        xksProblemAdapter.addDatas(list);
    }

    @Override
    public void updateData() {
        super.updateData();
    }

    @Override
    public void onResume() {
        super.onResume();
        if ("0".equals(PreferencesUtils.getString(activity, ConstData.YICHANGREFRESH, "1"))){
            PreferencesUtils.putString(activity, ConstData.YICHANGREFRESH, "1");
            activity.finish();
        }
    }
}
